<?php


namespace app\index\model;


use app\admin\model\MemberLevel;
use app\admin\model\UsersMember;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use wxpay\Wxsend;

class Order extends Model
{
    protected $name = 'admin_order';

    protected $autoWriteTimestamp = true;

    /**
     * 处理订单支付回调
     * @param $data
     * @return bool|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function orderNotify($data)
    {
        Log::write('刚进来订单支付回调' . json_encode($data), 'error');
        if (empty($data)) {
            return false;
        }

        // 查询订单是否存在
        $order = self::where('order_no', $data['out_trade_no'])->find();
        Log::write('进来订单支付回调查询订单是否存在' . json_encode($order), 'error');
        if (empty($order)) {
            return false;
        }

        $where = ['openid' => $data['openid']];
        if (isset($data['pay_type'])) {
            $where = ['pub_openid' => $data['openid']];
        }
        $users = UsersModel::where($where)->find();
        Log::write('进来订单支付回调查询用户信息是否存在' . json_encode($users), 'error');
        if (empty($users)) {
            return false;
        }

        $memberLevel = MemberLevel::where('id', $order->mid)->find();
        Db::startTrans();
        try {
            // validity 会员天数
            if ($memberLevel->validity >= 1) {
                $usersMember = UsersMember::where(['uid' => $users['id'], 'is_show' => 1])->find();
                if (!empty($usersMember)) {
                    // 更新会员到期时间
                    $endTime = UsersMember::setMemberExpireTime($memberLevel, $usersMember['end_time']);
                    $up = UsersMember::update(['end_time' => $endTime], ['uid' => $users['id'], 'is_show' => 1]);
                    $msg = '进来订单支付回调成功更新会员到期时间';
                    if (!$up) {
                        $msg = '进来订单支付回调更新会员到期时间失败';
                    }
                    Log::write($msg . json_encode($up), 'error');
                    $productName = '续费会员';
                } else {
                    // 新会员添加
                    $endTime = UsersMember::setMemberExpireTime($memberLevel, time());
                    $cr = UsersMember::create([
                        'uid' => $users['id'],
                        'unionid' => $users['unionid'],
                        'start_time' => time(),
                        'end_time' => $endTime,
                        'code' => generateCode(),
                    ]);
                    $msg1 = '进来订单支付回调新会员添加成功';
                    if (!$cr) {
                        $msg1 = '进来订单支付回调新会员添加失败';
                    }
                    Log::write($msg1 . json_encode($cr), 'error');
                    $productName = '购买会员';
                }
            }

            // 修改订单状态信息
            $order->status = 1;
            $order->pay_time = strtotime($data['time_end']);
            $order->save();
            Log::write('进来订单支付回调订单状态更新完毕', 'error');

            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            Log::write($e->getMessage(), 'error');

            return json(['code' => 10500, 'msg' => $e->getMessage()]);
        }

        if (isset($productName) && isset($endTime)) {
            $keyword1 = $productName;
            $keyword2 = '1份';
            $keyword3 = date('Y-m-d', $endTime);
            if ($users['pub_openid']) {
                Log::write('存在openid' . json_encode($users['pub_openid']), 'error');
                $send = new Wxsend();
                $send->sendMsg($users['pub_openid'], 1, $keyword1, $keyword2, $keyword3);
            }
        }

        return json(['code' => 10200, 'msg' => 'success']);
    }


}